#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <curl/curl.h>
#include <curl/types.h>
#include <curl/easy.h>

#include <pcre.h>

struct MemoryStruct {
  char *memory;
  size_t size;
};

char enter_reverse_mode[] = "\33[7m";
char exit_reverse_mode[] = "\33[0m";

static void *myrealloc(void *ptr, size_t size);

static void *myrealloc(void *ptr, size_t size)
{
  /* There might be a realloc() out there that doesn't like reallocing
     NULL pointers, so we take care of it here */
  if(ptr)
    return realloc(ptr, size);
  else
    return malloc(size);
}

static size_t
WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data)
{
  size_t realsize = size * nmemb;
  struct MemoryStruct *mem = (struct MemoryStruct *)data;

  mem->memory = myrealloc(mem->memory, mem->size + realsize + 1);
  if (mem->memory) {
    memcpy(&(mem->memory[mem->size]), ptr, realsize);
    mem->size += realsize;
    mem->memory[mem->size] = 0;
  }
  return realsize;
}

int main(int argc, char **argv)
{
  CURL *curl_handle;
  //const char *str_regex = "(www\\.[-_[:alnum:]]+\\.[[:lower:]]{2,4})";
  const char *str_regex = "<a href=(.*?)>";
  pcre *expr;
  const char *errstr;
  int erroffset;


  struct MemoryStruct chunk;

  chunk.memory=NULL; /* we expect realloc(NULL, size) to work */
  chunk.size = 0;    /* no data at this point */

  curl_global_init(CURL_GLOBAL_ALL);

  /* init the curl session */
  curl_handle = curl_easy_init();
  curl_easy_setopt(curl_handle, CURLOPT_URL, "http://tamarou.fr/");
  curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
  curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk);
  curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
  curl_easy_perform(curl_handle);
  curl_easy_cleanup(curl_handle);

  if (!(expr = pcre_compile(str_regex, PCRE_UTF8|PCRE_MULTILINE|PCRE_CASELESS, &errstr, &erroffset, 0))) {
   fprintf(stderr, "%s: %s\n", str_regex, errstr);
   return EXIT_FAILURE;
  }
  size_t len = strlen(chunk.memory);
  int matches[2];
  int offset = 0;
  int flags = 0;

   printf("Boub\n");
  while (0 < pcre_exec(expr, 0, chunk.memory, len, offset, flags, matches, 2)) {
   printf("%.*s%s%.*s%s",
        matches[0] - offset, chunk.memory + offset,
        enter_reverse_mode,
        matches[1] - matches[0], chunk.memory + matches[0],
        exit_reverse_mode);
   offset = matches[1];
   flags |= PCRE_NOTBOL;
  }

  if(chunk.memory){
    free(chunk.memory);
  }

  curl_global_cleanup();
  return 0;
}
